package com.naiterui.ehp.bs.patient.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.utils.StringUtils;
import com.naiterui.common.repository.page.PageParamVO;
import com.naiterui.common.repository.page.PageVO;
import com.naiterui.ehp.bp.constants.SwaggerTag;
import com.naiterui.ehp.bp.domain.PatientPersonDoctor;
import com.naiterui.ehp.bp.support.exception.BaseExceptionCodes;
import com.naiterui.ehp.bp.support.exception.PublicService;
import com.naiterui.ehp.bp.support.exception.ResponseVO;
import com.naiterui.ehp.bp.support.utils.JsonMapper;
import com.naiterui.ehp.bs.doctor.vo.PatientRemarkInfoVO;
import com.naiterui.ehp.bs.doctor.vo.PatientVo;
import com.naiterui.ehp.bs.doctor.vo.casefile.CaseListVO;
import com.naiterui.ehp.bs.patient.exception.ExceptionCodes;
import com.naiterui.ehp.bs.patient.service.IPatientDoctorService;
import com.naiterui.ehp.bs.patient.service.IPatientService;
import com.naiterui.ehp.bs.patient.service.IPatientSyncService;
import com.naiterui.ehp.bs.patient.utils.exception.PatientBusinessException;
import com.naiterui.ehp.bs.patient.vo.requestparam.PatientInquirerParam;
import com.naiterui.ehp.bs.patient.vo.requestparam.PatientParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

@Api(tags = SwaggerTag.BADACHU + SwaggerTag.USER_INFO)
@RequestMapping("ap/patientSync")
@Controller
public class ApPatientSyncController {
    private static final Logger LOGGER = LoggerFactory.getLogger(ApPatientController.class);

    @Autowired
    private IPatientSyncService patientSyncService;
    @Autowired
    private IPatientDoctorService patientDoctorService;

    // 添加患者信息
    @ResponseBody
    @RequestMapping(value = "savePatient", method = RequestMethod.POST)
    @ApiOperation(value = "添加患者信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = "patientId", value = "患者ID", required = true, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "nickName", value = "昵称", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "headUrl", value = "头像", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "gender", value = "性别(0女1男)", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "photo", value = "手机号", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "platform", value = "用户平台  10：八大处", required = true, dataType = "int", paramType = "query")})
    public ResponseVO<PatientParam> savePatient(PatientParam patientParam) throws Exception {
        LOGGER.info("添加患者信息, data {}", JsonMapper.toJson(patientParam));
        if(patientParam.getPatientId() == null || patientParam.getPlatform() == null){
            LOGGER.error("添加患者信息; illegal param : patientId is null");
            throw new PatientBusinessException(ExceptionCodes.PARAM_ERROR);
        }
        patientSyncService.savePatient(patientParam);
        return PublicService.returnResponseVO(ExceptionCodes.SUCCESS, patientParam);
    }

    // 添加就诊人
    @ResponseBody
    @RequestMapping(value = "savePatientInquirer", method = RequestMethod.POST)
    @ApiOperation(value = "添加患者就诊人信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = "patientId", value = "患者ID", required = true, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "inquirerId", value = "就诊人ID", required = true, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "relation", value = "关系 0：本人 1：父母 2：子女 3：配偶 4：其他", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "姓名", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "idCard", value = "身份证号", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "手机号码", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "address", value = "居住地址", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "contactName", value = "联系人姓名", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "contactPhone", value = "联系人手机号码", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "isDefault", value = "是否默认 0：否 1：是", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "platform", value = "用户平台  10：八大处", required = true, dataType = "int", paramType = "query")})
    public ResponseVO savePatientInquirer(PatientInquirerParam patientInquirerParam) throws Exception {
        LOGGER.info("添加患者就诊人信息, data {}", JsonMapper.toJson(patientInquirerParam));
        // 判断必传参数
        if(patientInquirerParam.getPatientId() == null || patientInquirerParam.getInquirerId() == null || patientInquirerParam.getRelation() == null
                || StringUtils.isEmpty(patientInquirerParam.getName()) || StringUtils.isEmpty(patientInquirerParam.getIdCard())
                || StringUtils.isEmpty(patientInquirerParam.getPhone())
                || patientInquirerParam.getPlatform() == null){
            LOGGER.error("添加患者就诊人信息; illegal param : patientId is null");
            throw new PatientBusinessException(ExceptionCodes.PARAM_ERROR);
        }
        return patientSyncService.savePatientInquirer(patientInquirerParam);
    }

    // 删除就诊人
    @ResponseBody
    @RequestMapping(value = "deletePatientInquirer", method = RequestMethod.POST)
    @ApiOperation(value = "删除患者就诊人信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = "patientId", value = "患者ID", required = true, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "inquirerId", value = "就诊人ID", required = true, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "platform", value = "用户平台  10：八大处", required = true, dataType = "int", paramType = "query")})
    public ResponseVO<Void> deletePatientInquirer(PatientInquirerParam patientInquirerParam) throws Exception {
        LOGGER.info("删除患者就诊人信息, data {}", JsonMapper.toJson(patientInquirerParam));
        // 判断必传参数
        if(patientInquirerParam.getPatientId() == null || patientInquirerParam.getInquirerId() == null || patientInquirerParam.getPlatform() == null){
            LOGGER.error("删除患者就诊人信息; illegal param : patientId is null");
            throw new PatientBusinessException(ExceptionCodes.PARAM_ERROR);
        }
        patientSyncService.deletePatientInquirer(patientInquirerParam);
        return PublicService.returnResponseVO(ExceptionCodes.SUCCESS);
    }

    // 添加患者医生关系
    @ResponseBody
    @RequestMapping(value = "addPersonalDoctor", method = RequestMethod.POST)
    @ApiOperation(value = "添加患者医生关系", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = "doctorId", value = "医生ID", required = true, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "patientId", value = "就诊人ID", required = true, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "source", value = "医生来源：0:公众号,1:互联网医院,2:推荐咨询活动,3:患者找医生, 4:微信小程序,5:线上咨询", required = true, dataType = "long", paramType = "query")})
    public ResponseVO<Void> add(Long patientId, Long doctorId, Integer firstRecom, Integer source) throws Exception {
        LOGGER.info("添加患者医生接口  patientId: {},doctorId: {},firstRecom: {},source: {}", patientId, doctorId, firstRecom, source);
        if (patientId == null || doctorId == null || source == null) {
            LOGGER.error("添加患者医生接口 参数错误，patientId: {},doctorId: {},firstRecom: {},source: {}", patientId, doctorId, firstRecom, source);
            throw new PatientBusinessException(ExceptionCodes.PARAM_ERROR);
        }
        if (firstRecom == null) {
            firstRecom = 0;
        }
        patientDoctorService.addPersonalDoctor(doctorId, patientId, firstRecom, source);
        return PublicService.returnResponseVO(BaseExceptionCodes.SUCCESS);
    }

    // 医生审核患者（接受）
    @ResponseBody
    @RequestMapping(value = "auditDoctorPatient", method = RequestMethod.POST)
    @ApiOperation(value = "医生审核患者（接受）", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = "doctorId", value = "医生ID", required = true, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "patientId", value = "就诊人ID", required = true, dataType = "long", paramType = "query")})
    public ResponseVO<Void> auditDoctorPatient(Long doctorId, Long patientId) throws Exception {
        if (patientId == null || doctorId == null) {
            LOGGER.error("医生审核患者（接受） 参数错误，patientId: {},doctorId: {}", patientId, doctorId);
            throw new PatientBusinessException(ExceptionCodes.PARAM_ERROR);
        }
        return patientSyncService.auditDoctorPatient(doctorId, patientId);
    }

    // 医生解除患者关系
    @ResponseBody
    @RequestMapping(value = "removeDoctorPatient", method = RequestMethod.POST)
    @ApiOperation(value = "医生解除患者关系", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = "doctorId", value = "医生ID", required = true, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "patientId", value = "就诊人ID", required = true, dataType = "long", paramType = "query")})
    public ResponseVO<Void> removeDoctorPatient(Long doctorId, Long patientId) throws Exception {
        if (patientId == null || doctorId == null) {
            LOGGER.error("医生解除患者关系 参数错误，patientId: {},doctorId: {}", patientId, doctorId);
            throw new PatientBusinessException(ExceptionCodes.PARAM_ERROR);
        }
        return patientSyncService.removeDoctorPatient(doctorId, patientId);
    }

    // 医生查询待审核患者列表(分页)
    @ResponseBody
    @RequestMapping(value = "queryDoctorPatientAuditPage", method = RequestMethod.POST)
    @ApiOperation(value = "医生查询待审核患者列表(分页)", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = "doctorId", value = "医生ID", required = true, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "num", value = "每页记录数", required = true, dataType = "int", paramType = "query")})
    public ResponseVO<PageVO<PatientVo>> queryDoctorPatientAuditPage(Long doctorId, PageParamVO pageParamVO) throws Exception {
        if (doctorId == null) {
            LOGGER.error("医生查询待审核患者列表(分页) 参数错误，doctorId: {}", doctorId);
            throw new PatientBusinessException(ExceptionCodes.PARAM_ERROR);
        }
        // 已经分页并排序的患者列表
        PageVO<PatientVo> pagedNewPatientList = patientSyncService.queryDoctorPatientAuditPage(doctorId, pageParamVO);
        return PublicService.returnResponseVO(ExceptionCodes.SUCCESS, pagedNewPatientList);
    }

    // 查询医生、患者是否是好友
    @ResponseBody
    @RequestMapping(value = "queryDoctorPatientIsFriend", method = RequestMethod.POST)
    @ApiOperation(value = "查询医生、患者是否是好友", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = "doctorId", value = "医生ID", required = true, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "patientId", value = "就诊人ID", required = true, dataType = "long", paramType = "query")})
    public ResponseVO<Void> queryDoctorPatientIsFriend(Long doctorId, Long patientId) throws Exception {
        if (patientId == null || doctorId == null) {
            LOGGER.error("查询医生、患者是否是好友 参数错误，patientId: {},doctorId: {}", patientId, doctorId);
            throw new PatientBusinessException(ExceptionCodes.PARAM_ERROR);
        }
        return patientSyncService.queryDoctorPatientIsFriend(doctorId, patientId);
    }


    // 查询医生今日患者数量
    @ResponseBody
    @RequestMapping(value = "queryDoctorPatientToday", method = RequestMethod.POST)
    @ApiOperation(value = "查询医生今日患者数量", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = "doctorId", value = "医生ID", required = true, dataType = "long", paramType = "query")})
    public ResponseVO<Long> queryDoctorPatientToday(Long doctorId) throws Exception {
        if (doctorId == null) {
            LOGGER.error("查询医生今日患者数量 参数错误，doctorId: {}", doctorId);
            throw new PatientBusinessException(ExceptionCodes.PARAM_ERROR);
        }
        Long patientNum = patientSyncService.queryDoctorPatientToday(doctorId);
        return PublicService.returnResponseVO(ExceptionCodes.SUCCESS, patientNum);
    }
}
